package com.example.backend.Utils;

import com.example.backend.model.WeatherData;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.json.JSONObject;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class WeatherUtil {

    private static String getSoapRequest(String city) {
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
                + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
                + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                + "<soap:Body>    <getWeather xmlns=\"http://WebXml.com.cn/\">" + "<theCityCode>" + city
                + "</theCityCode>    </getWeather>" + "</soap:Body></soap:Envelope>");
        return sb.toString();
    }

    private static InputStream getSoapInputStream(String city) throws Exception {
        try {
            String soap = getSoapRequest(city);
            if (soap == null) {
                return null;
            }
            URL url = new URL("http://www.webxml.com.cn/WebServices/WeatherWS.asmx");
            URLConnection conn = url.openConnection();
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Length", Integer.toString(soap.length()));
            conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            conn.setRequestProperty("SOAPAction", "http://WebXml.com.cn/getWeather");
            OutputStream os = conn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
            osw.write(soap);
            osw.flush();
            osw.close();
            InputStream is = conn.getInputStream();
            return is;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public WeatherData getWeather(String city) {
        try {
            Document doc;
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputStream is = getSoapInputStream(city);
            doc = db.parse(is);
            NodeList nl = doc.getElementsByTagName("string");

            WeatherData weatherData = new WeatherData();
            List<WeatherData.Forecast> forecastList = new ArrayList<>();

            weatherData.setCity(getNodeValue(nl.item(1))); // 只取城市名称
            weatherData.setDateTime(getNodeValue(nl.item(3)));

            // 提取天气实况数据
            String currentWeather = getNodeValue(nl.item(4));
            weatherData.setCurrentTemperature(parseWeatherDetail(currentWeather, "气温"));
            weatherData.setWind(parseWeatherDetail(currentWeather, "风向/风力"));
            weatherData.setHumidity(parseWeatherDetail(currentWeather, "湿度"));

            // 提取各类指数数据
            weatherData.setUvIndex(trimIndex(getNodeValue(nl.item(5))));
            String[] indices = getNodeValue(nl.item(6)).split("\n");
            weatherData.setColdIndex(trimIndex(indices.length > 0 ? indices[0] : ""));
            weatherData.setSportIndex(trimIndex(indices.length > 1 ? indices[1] : ""));
            weatherData.setAllergyIndex(trimIndex(indices.length > 2 ? indices[2] : ""));
            weatherData.setDressIndex(trimIndex(indices.length > 3 ? indices[3] : ""));
            weatherData.setCarWashIndex(trimIndex(indices.length > 4 ? indices[4] : ""));
            weatherData.setUvIndex(trimIndex(indices.length > 5 ? indices[5] : ""));

            // 处理天气预报部分
            for (int count = 7; count + 4 < nl.getLength(); count += 5) {
                WeatherData.Forecast forecast = new WeatherData.Forecast();
                String dateAndWeather = getNodeValue(nl.item(count));
                forecast.setDate(parseDate(dateAndWeather));
                forecast.setWeather(parseWeather(dateAndWeather));
                forecast.setTemperature(getNodeValue(nl.item(count + 1)));
                forecast.setWind(getNodeValue(nl.item(count + 2)));
                forecast.setIcon1(getNodeValue(nl.item(count + 3)));
                forecast.setIcon2(getNodeValue(nl.item(count + 4)));
                forecastList.add(forecast);
            }

            weatherData.setForecast(forecastList);

            weatherData.formSuggestions();

//            // Convert weatherData to JSON string
//            JSONObject jsonObject = new JSONObject(weatherData);
//            return jsonObject.toString();
            return weatherData;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private String getNodeValue(Node node) {
        if (node != null && node.getFirstChild() != null) {
            return node.getFirstChild().getNodeValue();
        }
        return "";
    }

    private String parseWeatherDetail(String weatherDetails, String key) {
        Pattern pattern = Pattern.compile(key + "：([^；]+)");
        Matcher matcher = pattern.matcher(weatherDetails);
        if (matcher.find()) {
            return matcher.group(1).trim();
        }
        return "";
    }

    private String trimIndex(String indexDetail) {
        if (indexDetail.contains("：")) {
            return indexDetail.split("：")[1].trim();
        }
        return indexDetail;
    }

    private String parseDate(String dateAndWeather) {
        return dateAndWeather.split(" ")[0].trim();
    }

    private String parseWeather(String dateAndWeather) {
        return dateAndWeather.split(" ")[1].trim();
    }
}
